package com.agileai.portal.bizmoduler.sso;

import java.util.ArrayList;
import java.util.List;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.bizmoduler.core.BaseService;
import com.agileai.util.ListUtil;
import com.agileai.util.MapUtil;
import com.agileai.util.StringUtil;

public class UserSSOServiceImpl extends BaseService implements UserSSOService {

	public void addUserApplication(String appId, String userId) {
		String ticketId = KeyGenerator.instance().genKey();
		DataParam param = new DataParam();
		param.put("TICKET_ID",ticketId,"USER_ID",userId,"APP_ID",appId,"IS_VISIABLE","N");
		int newSort = this.getMaxSortId(userId);
		param.put("APP_SORT",newSort);
		String statementId = sqlNameSpace+"."+"insertTicket";
		this.daoHelper.insertRecord(statementId, param);
		
		List<DataParam> params = this.findInitParams(appId);
		statementId = sqlNameSpace+"."+"insertTicketEntry";
		for (int i=0;i < params.size();i++){
			DataParam temParam = params.get(i);
			temParam.put("TICKET_ID",ticketId);
		}
		this.daoHelper.batchInsert(statementId, params);
	}
	private int getMaxSortId(String userId){
		int result = 1;
		DataParam param = new DataParam("userId",userId);
		String statementId = sqlNameSpace+"."+"getMaxSortRecord";
		DataRow row = this.daoHelper.getRecord(statementId, param);
		if (!MapUtil.isNullOrEmpty(row)){
			result = row.getInt("MAX_SORT")+1;
		}
		return result;
	}
	private List<DataParam> findInitParams(String appId){
		List<DataRow> result = null;
		String statementId = sqlNameSpace+"."+"findInitParams";
		DataParam param = new DataParam("appId",appId);
		result = this.daoHelper.queryRecords(statementId, param);
		return ListUtil.toParamList(result);
	}

	private String sortField = "APP_SORT";
	private String idField = "TICKET_ID";
	public void changeApplicationSort(String userId,String ticketId, boolean isUp) {
		String statementId = sqlNameSpace+"."+"findRecords";
		DataParam param = new DataParam("userId",userId);
		List<DataRow> records = this.daoHelper.queryRecords(statementId, param);
		DataRow curRow = null;
		String curSort = null;
		
		if (isUp){
			DataRow beforeRow = null;
			for (int i=0;i < records.size();i++){
				DataRow row = records.get(i);
				String tempMenuId = row.stringValue(idField);
				if (ticketId.equals(tempMenuId)){
					curRow = row;
					beforeRow = records.get(i-1);
					break;
				}
			}
			curSort = curRow.stringValue(sortField);
			String beforeSort = beforeRow.stringValue(sortField);;
			curRow.put(sortField,beforeSort);
			beforeRow.put(sortField,curSort);
			this.updateCurrentRecord(curRow.toDataParam());
			this.updateCurrentRecord(beforeRow.toDataParam());
		}else{
			DataRow nextRow = null;
			for (int i=0;i < records.size();i++){
				DataRow row = records.get(i);
				String tempMenuId = row.stringValue(idField);
				if (ticketId.equals(tempMenuId)){
					curRow = row;
					nextRow = records.get(i+1);
					break;
				}
			}
			curSort = curRow.stringValue(sortField);
			String nextSort = nextRow.stringValue(sortField);
			curRow.put(sortField,nextSort);
			nextRow.put(sortField,curSort);
			this.updateCurrentRecord(curRow.toDataParam());
			this.updateCurrentRecord(nextRow.toDataParam());
		}
	}
	private void updateCurrentRecord(DataParam param){
		String statementId = sqlNameSpace+"."+"updateTicket";
		this.daoHelper.updateRecord(statementId, param);
	}
	
	public void delUserApplication(String ticketId) {
		DataParam param = new DataParam("TICKET_ID",ticketId);
		String statementId = sqlNameSpace+"."+"deleteTicket";
		this.daoHelper.deleteRecords(statementId, param);
		
		statementId = sqlNameSpace+"."+"deleteTicketEntry";
		this.daoHelper.deleteRecords(statementId, param);
	}

	public void editUserApplication(DataParam param,List<DataParam> paramEntrys) {
		String statementId = sqlNameSpace+"."+"updateTicket";
		this.daoHelper.updateRecord(statementId, param);
		
		statementId = sqlNameSpace+"."+"deleteTicketEntry";
		this.daoHelper.deleteRecords(statementId, param);
		
		statementId = sqlNameSpace+"."+"insertTicketEntry";
		this.daoHelper.batchInsert(statementId, paramEntrys);
	}

	public List<DataRow> findEditApplications(String userId) {
		List<DataRow> result = null;
		String statementId = sqlNameSpace+"."+"findRecords";
		DataParam param = new DataParam("userId",userId);
		result = this.daoHelper.queryRecords(statementId, param);
		return result;
	}
	
	public SSOTicket findSSOTicket(String ticketId) {
		SSOTicket ssoTicket = null;
		String statementId = sqlNameSpace+"."+"getTicketRecord";
		DataParam param = new DataParam("ticketId",ticketId);
		DataRow row = this.daoHelper.getRecord(statementId, param);
		if (!MapUtil.isNullOrEmpty(row)){
			String appType = row.stringValue("APP_TYPE");
			String authType = row.stringValue("APP_AUTH_TYPE");
			ssoTicket = new SSOTicket();
			ssoTicket.setAppType(appType);
			ssoTicket.setAuthType(authType);
			ssoTicket.setAppId(row.stringValue("APP_ID"));
			ssoTicket.setAppURL(row.stringValue("APP_PATH"));
			ssoTicket.setExtURL(row.stringValue("EXT_URL"));
			ssoTicket.setUserId(row.stringValue("USER_ID"));
			
			if (AppType.BS.equals(appType) && AuthType.FORM.equals(authType)){
				ssoTicket.setTimeoutMinutes(row.getInt("APP_TIMEOUT",0));					
			}
			
			statementId = sqlNameSpace+"."+"getTicketEntryRecords";
			List<DataRow> entrys = this.daoHelper.queryRecords(statementId, param);
			for (int i=0;i < entrys.size();i++){
				DataRow entry = entrys.get(i);
				String paramCode = entry.stringValue("PARAM_CODE");
				if (RedirectURLKey.equals(paramCode)){
					ssoTicket.setRedirectURL(entry.stringValue("VALUE_EXPRESSION"));
				}else{
					SSOTicketEntry ssoTicketEntry = new SSOTicketEntry();
					ssoTicketEntry.setParamCode(paramCode);
					ssoTicketEntry.setParamValue(entry.stringValue("PARAM_VALUE"));
					ssoTicketEntry.setEncription("Y".equals(entry.stringValue("ENCRIPTION")));
					ssoTicketEntry.setValueExpression(entry.stringValue("VALUE_EXPRESSION"));
					ssoTicket.getSsoTicketEntryList().add(ssoTicketEntry);
				}
			}
		}
		return ssoTicket;
	}	
	public DataRow findUserApplication(String ticketId) {
		DataParam param = new DataParam("ticketId",ticketId);
		String statementId = sqlNameSpace+"."+"getTicketRecord";
		return this.daoHelper.getRecord(statementId, param);
	}	
	public List<DataRow> findUserMappingItem(String ticketId) {
		List<DataRow> result = new ArrayList<DataRow>();
		String statementId = sqlNameSpace+"."+"getTicketEntryRecords";
		DataParam param = new DataParam("ticketId",ticketId);
		List<DataRow> records = this.daoHelper.queryRecords(statementId, param);
		for (int i=0;i < records.size();i++){
			DataRow row = records.get(i);
			String valueExpression = row.stringValue("VALUE_EXPRESSION");
			if (StringUtil.isNullOrEmpty(valueExpression)){
				result.add(row);
			}
		}
		return result;
	}
	public List<DataRow> findViewApplications(String userId) {
		List<DataRow> result = null;
		String statementId = sqlNameSpace+"."+"findRecords";
		DataParam param = new DataParam("userId",userId,"isVisiable","Y");
		result = this.daoHelper.queryRecords(statementId, param);
		return result;
	}
	@Override
	public boolean isExistRelApplication(String appId) {
		boolean result = false;
		String statementId = sqlNameSpace+"."+"getRelAppCount";
		DataParam param = new DataParam("appId",appId);
		DataRow row = this.daoHelper.getRecord(statementId, param);
		String count = row.stringValue("REL_COUNT");
		int relCount = Integer.parseInt(count);
		result = (relCount > 0);
		return result;
	}
	@Override
	public SSOTicket findDummySSOTicket(String appId) {
		SSOTicket ssoTicket = null;
		String statementId = sqlNameSpace+"."+"getTicketRecordByAppId";
		DataParam param = new DataParam("ssoAppId",appId);
		DataRow row = this.daoHelper.getRecord(statementId, param);
		if (!MapUtil.isNullOrEmpty(row)){
			String appType = row.stringValue("APP_TYPE");
			String authType = row.stringValue("APP_AUTH_TYPE");
			
			ssoTicket = new SSOTicket();
			ssoTicket.setAppType(appType);
			ssoTicket.setAuthType(authType);
			ssoTicket.setAppId(row.stringValue("APP_ID"));
			ssoTicket.setAppURL(row.stringValue("APP_PATH"));
			ssoTicket.setExtURL(row.stringValue("EXT_URL"));
			
			if (AppType.BS.equals(appType) && AuthType.FORM.equals(authType)){
				ssoTicket.setTimeoutMinutes(row.getInt("APP_TIMEOUT",0));					
			}
			
			statementId = sqlNameSpace+"."+"getEntryRecords";
			List<DataRow> entrys = this.daoHelper.queryRecords(statementId, param);
			for (int i=0;i < entrys.size();i++){
				DataRow entry = entrys.get(i);
				String paramCode = entry.stringValue("PARAM_CODE");
				if (RedirectURLKey.equals(paramCode)){
					ssoTicket.setRedirectURL(entry.stringValue("VALUE_EXPRESSION"));
				}else{
					SSOTicketEntry ssoTicketEntry = new SSOTicketEntry();
					ssoTicketEntry.setParamCode(paramCode);
					ssoTicketEntry.setParamValue(entry.stringValue("PARAM_VALUE"));
					ssoTicketEntry.setEncription("Y".equals(entry.stringValue("ENCRIPTION")));
					ssoTicketEntry.setValueExpression(entry.stringValue("VALUE_EXPRESSION"));
					ssoTicket.getSsoTicketEntryList().add(ssoTicketEntry);					
				}
			}
		}
		return ssoTicket;
	}	
}